package cn.edu.zafu.bigdata.zyf;

import java.io.*;
import java.net.*;

public class TimeServer {
    public static void main(String[] args) {
        int port = 1234; // 服务端监听的端口
        try (DatagramSocket socket = new DatagramSocket(port)) {
            System.out.println("Time server is running...");

            while (true) {
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                socket.receive(receivePacket);

                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Client says: " + sentence);

                String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());
                String output = "Current time is: " + currentTime;

                sendData = output.getBytes();

                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                socket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}